<template>
  <auth-page>
    <view class="shop" :style="{ '--themeColor': themeColor }">
      <view class="shoping" id="shoping">
        <view class="icon" @click="handleMixinAuth(showDialog)">
          <xh-img src="img/pub/cart.png" />
          <view
            class="falg"
            :class="[cartNum >= 10 ? 'falgMax' : '']"
            v-if="cartNum > 0"
          >
            <text v-if="cartNum > 99">99+</text>
            <text v-else>{{ cartNum }}</text>
          </view>
        </view>

        <view class="right">
          <view class="price"><span>¥</span>{{ cartPrice }}</view>
          <view
            :class="[
              'btn',
              shopStatus != 0 || !cartList || isError ? 'no-open' : '',
            ]"
            @click="handleMixinAuth(closeAccount)"
          >
            {{ shopStatus == 0 ? "去结算" : "门店已打烊" }}
          </view>
        </view>
      </view>
      <u-popup
        :show="show"
        @close="close"
        :round="4"
        @touchmove.stop.prevent
        :safeAreaInsetBottom="false"
      >
        <view class="shoping-pop">
          <view class="pop-top">
            <view class="left">已选商品（共{{ cartNum }}件）</view>
            <view class="right" @click="clearCart()">清空</view>
          </view>

          <scroll-view
            scroll-y="true"
            v-if="cartList.length >= 4"
            :class="['list']"
          >
            <view v-for="item in cartList" :key="item.skuId">
              <cartContent :good="item" />
            </view>
          </scroll-view>
          <view v-else>
            <view v-for="item in cartList" :key="item.skuId">
              <cartContent :good="item" />
            </view>
          </view>
        </view>
      </u-popup>
      <dine-way-pop :visible.sync="showDine" @exportDinner="closeAccount" />
    </view>
  </auth-page>
</template>

<script>
import { mapState } from "vuex";
import cartContent from "./cartContent";
import dineWayPop from "../dineWayPop";
import { queryCartList } from "@/service/api/sp-store/commodity.js";
import { clearCart } from "@/service/api/sp-store/commodity.js";
import { mixinAuth } from "@/mixin/sp-common/mixin-auth";

export default {
  mixins: [mixinAuth],
  data() {
    return {
      isOpentime: true,
      show: false,
      showDine: false,
      cartList: [],
      cartHeight: 0,
      isError: false,
      isIos: false,
    };
  },
  components: {
    cartContent,
    dineWayPop,
  },
  computed: {
    ...mapState("sp-store/index", [
      "dineParams",
      "cartData",
      "cartNum",
      "pubShopId",
      "cartPrice",
      "shopStatus",
      "distributionType",
    ]),
    ...mapState("sp-common/base", ["themeColor"]),
  },
  watch: {
    // 监听购物车数据变化
    cartData: {
      handler(newVal) {
        this.isError = false;
        this.cartList = newVal.items;
        this?.cartList.forEach((el) => {
          if (el.errorCode === 55101 || el.errorCode === 55102) {
            this.isError = true;
          }
        });
      },
      deep: true,
    },
  },
  mounted() {
    this.cartList = this.cartData.items;
    this.$nextTick((res) => {
      uni
        .createSelectorQuery()
        .in(this)
        .select("#shoping")
        .boundingClientRect((data) => {
          this.cartHeight = data.height;
        })
        .exec();
      uni.getSystemInfo({
        success: (res) => {
          this.isIos = res.osName === "ios";
        },
      });
    });
  },
  methods: {
    showDialog() {
      this.$store.dispatch("sp-store/index/initCart");
      if (!this.cartList) return;
      this.show = true;
    },
    close() {
      this.show = false;
    },
    // 结算功能
    async closeAccount() {
      let shopSta = await this.$myTool.verifyShop();
      let cartStatus = await this.verifyCartStatus();
      let {
        dineParams,
        cartData: { storeId, items },
        distributionType: { datas },
      } = this;
      if (cartStatus) {
        this.$store.dispatch("sp-store/index/initCart");
        return;
      }
      if (shopSta) {
        if (datas.length < 2) {
          //就餐方式只有1种，则无需显示弹窗
          this.$store.commit("sp-store/index/SET_DINE", datas[0]);
        } else {
          if (!dineParams) {
            this.showDine = true;
            return;
          }
        }
        let queryParams = {
          source: 0,
          storeId,
          items,
        };
        uni.navigateTo({
          url: `pages/sp-order/pages/store-order-submit/index`,
          success: (res) => {
            res.eventChannel.emit("order", { data: queryParams });
            // this.$store.commit('sp-store/index/SET_ORDER_DATA',queryParams);
          },
        });
      }
    },
    async verifyCartStatus() {
      let { pubShopId } = this;
      let { items: cartList } = await queryCartList({ pubShopId });
      let status = false;
      for (let i = 0; i <= cartList.length - 1; i++) {
        if (
          cartList[i].errorCode === 55101 ||
          cartList[i].errorCode === 55102
        ) {
          status = true;
        }
      }
      return status;
    },
    // 清空购物车
    clearCart() {
      uni.showModal({
        content: "是否要清空购物车？",
        success: (res) => {
          if (res.confirm) {
            let { pubShopId } = this;
            clearCart({ pubShopId }).then((res) => {
              if (!res) {
                this.$store.dispatch("sp-store/index/initCart");
                this.close();
              }
            });
          }
        },
      });
    },
    exportHeight() {
      return this.cartHeight;
    },
  },
};
</script>

<style lang="scss" scoped>
.shoping {
  position: fixed;
  width: calc(100% - 60rpx);
  left: 0;
  bottom: 0;
  background: #fff;
  padding: 15rpx 30rpx;
  display: flex;
  justify-content: space-between;
  z-index: 10076;
  border-top: 1px solid #ececec;
  .icon {
    width: 90rpx;
    height: 90rpx;
    position: relative;
    margin-right: 30rpx;
    .falg {
      min-width: 26rpx;
      padding: 2rpx;
      height: 26rpx;
      border-radius: 26rpx;
      // padding: 0 5rpx;
      // padding: 8rpx;
      background: var(--theme-color);
      // border-radius: 20rpx;
      position: absolute;
      right: -16rpx;
      bottom: 0;
      font-size: 26rpx;
      font-weight: 500;
      color: #ffffff;
      text-align: center;
      // line-height: 30rpx;
      line-height: 26rpx;
    }
    .falgMax {
      padding: 2rpx 10rpx;
    }
  }
  .right {
    display: flex;
    flex: 1;
    justify-content: space-between;
    align-items: center;
    .btn {
      width: 180rpx;
      height: 80rpx;
      background: var(--theme-color);
      border-radius: 40rpx;
      font-size: 29rpx;
      font-weight: 500;
      color: #ffffff;
      text-align: center;
      line-height: 80rpx;
      border-top: 1px solid #ececec;
    }
    .no-open {
      opacity: 0.5;
      pointer-events: none;
    }
  }
}
.shoping-pop {
  max-height: calc(66vh - 230rpx);
  overflow-y: scroll;
  padding: 100rpx 0 130rpx 30rpx;
  display: flex;
  flex-direction: column;
  .pop-top {
    display: flex;
    justify-content: space-between;
    width: calc(100% - 60rpx);
    background-color: #ffffff;
    align-items: center;
    z-index: 1;
    font-size: 29rpx;
    font-weight: 500;
    color: #181818;
    position: absolute;
    top: 0;
    left: 0rpx;
    padding: 30rpx;
    border-bottom: 1rpx solid #ececec;
    border-radius: 8rpx 8rpx 0px 0px;
    .right {
      font-size: 27rpx;
      font-weight: 500;
      color: #888888;
    }
  }
  .list {
    height: calc(66vh - 230rpx);
    &::-webkit-scrollbar {
      display: none;
    }
  }
}
</style>
